<template>
  <!-- v-touch:right="onSwipeRight" -->

  <div id="app">
    <div v-transfer-dom>
      <!-- <loading :show="isLoading" text="加载中" style="z-index: 9999"></loading> -->
    </div>
    <transition :name="tansitionName">
      <keep-alive :include="['dangerList','qualityLists']">
        <router-view class="transition-view"></router-view>
      </keep-alive>
    </transition>
  </div>
</template>

<script>
var $vue = {};
export default {
  name: "app",
  mounted() {},
  beforeCreate() {
    //全局使用$vue代替this
    $vue = this;
  },
  created() {
    this.onLoad();
  },
  data() {
    return {
      tansitionName: "fade",
      // socket: "",
      path: "ws://qhsz.ecidi.com:8001/qhszpm/badge",
    };
  },
  methods: {
    // open: function() {
    //   //console.log("socket连接成功");
    //   this.send();
    // },
    // send() {
    //   //console.log(this.userId)
    //   //console.log(this.roleIDs)
    //   this.socket.send(this.userId + "&" + this.roleIDs);
    // },
    error: function() {
      // console.log("连接错误");
    },
    getMessage: function(msg) {
      console.log(msg.data);
      var num = msg.data.substring(0, msg.data.indexOf("&"));
      var messageto = msg.data.substring(msg.data.indexOf("&") + 1);
      //console.log(num)
      //console.log(messageto)
      //console.log(this.userId)
      // console.log(localStorage.username)
      if (messageto == localStorage.username) {
        this.$store.commit("setBadge", num);
        cordova.plugins.notification.badge.set($vue.$store.state.badge);
        //console.log(this.$store.state.badge);
      }
    },
    // close: function() {
    //   // console.log("socket已经关闭");
    //   this.socket.close();
    // },
    //页面加载后添加各事件监听
    onLoad() {
      document.addEventListener("deviceready", this.onDeviceReady, false);
    },
    getBadge() {
      console.log("进来了吗？")
      this.$ajax({
        method: "post",
        url: this.COMMON_URL,
        data: {
          _method: "HOME_FIX_PERMISSION_MENU.updateDataInTimeNew",
          userId: this.userId,
          roleIDs: this.roleIDs
        },
        async: false
      }).then(res => {
        this.$store.commit("setBadge", res.data.sum);
        console.log("消息数",$vue.$store.state.badge)
        cordova.plugins.notification.badge.set($vue.$store.state.badge);
      });
    },
    //Cordova加载完毕
    onDeviceReady() {
      if(device.platform == "iOS"){
        wkWebView.injectCookie('http://jgbim.qhfct.com:9000/qhszpm')
      }
      this.$store.commit("setSQLiteDB",window.sqlitePlugin.openDatabase({name: 'mydb', location: 'default'}))
      document.addEventListener(
        "pause",
        () => {
          // if (typeof WebSocket === "undefined") {
          //   alert("您的浏览器不支持socket");
          // } else {
          //   // 实例化socket
          //   // $vue.socket = new WebSocket($vue.path);
          //   // 监听socket连接
          //   // $vue.socket.onopen = $vue.open;
          //   // 监听socket错误信息
          //   // $vue.socket.onerror = $vue.error;
          //   // 监听socket消息
          //   // $vue.socket.onmessage = $vue.getMessage;
          // }
          $vue.getBadge();
          setInterval($vue.getBadge, 300000);
          //console.log("pause之前",$vue.$store.state.systemCount+$vue.$store.state.taskListCount)
          //console.log("pause"); //退出，后台运行
        },
        false
      );
      document.addEventListener("resume", this.getNums, false);
      //cordova.plugins.notification.badge.set(this.badge);
      this.hotPush(); //热更新
      document.addEventListener("backbutton", this.eventBackButton, false); //监听安卓物理回退事件
      console.log(StatusBar);
      // StatusBar.backgroundColorByHexString("#FFF") //改变状态栏颜色
      // if (cordova.platformId == 'android') {
      //     // StatusBar.overlaysWebView(true);
      //     StatusBar.backgroundColorByHexString('#33000000');//前两位设置透明度
      // }
      navigator.splashscreen.hide();
      // setTimeout(function() {
      //     navigator.splashscreen.hide();
      // }, 1000);
    },
    //获取任务待办数和消息数
    getNums() {
      var total = 0;
      this.$ajax({
        method: "post",
        url: this.COMMON_URL,
        data: {
          _method: "formflow.getTaskListCount",
          filter: "( flag in ('0','1','201','401'))"
        }
      }).then(res => {
        // console.log("shenmedongxi",res);
        this.$store.commit("setTaskListCount", res.data.data);
      });

      this.$ajax({
        method: "post",
        url: this.COMMON_URL,
        data: {
          _method: "SYS_NOTICE.getNotice",
          loginUserId: this.userId
        }
      })
        .then(res => {
          // console.log("denglu1111",res);
          total = total + res.data.noticeList.length;
          this.$store.commit("setSystemCount", total);
        })
        .catch(err => {
          console.log(err);
        });
        cordova.plugins.notification.badge.set(
            $vue.$store.state.systemCount + $vue.$store.state.taskListCount
        );

      //    this.$ajax({
      //   method: 'post',
      //   url: this.COMMON_URL,
      //   data: {
      //     _method : "EMERGENCYNOTICE.getNews",
      //   },
      // })
      //   .then(res => {
      //     // console.log("shenmedongxi",res);
      //     // console.log("denglu",res);
      //     total = total + res.data.data.length;
      //   })
      //   .catch(err => {
      //     console.log(err)
      //   }).then(()=>{
      //     this.$ajax({
      //       method: 'post',
      //     url: this.COMMON_URL,
      //     data: {
      //       _method : "SYS_NOTICE.getNotice",
      //       loginUserId : this.userId
      //     },
      //     }).then(res => {
      //       // console.log("denglu1111",res);
      //       total = total + res.data.noticeList.length
      //       this.$store.commit("setSystemCount",total);
      //     })
      //     .catch(err => {
      //       console.log(err)
      //     })
      //   })
    },
    //返回键点击响应
    eventBackButton() {
      if (this.$route.name == "login") {
        document.addEventListener("backbutton", this.exitApp, false); //绑定退出事件
      } else if (this.$route.meta.toast) {
        //在home页，与router/index.js对应
        //使用toast插件显示 提示信息
        this.$vux.toast.show({
          type: "text",
          text: "再点一次退出!",
          position: "bottom"
        });
        document.removeEventListener("backbutton", this.eventBackButton, false); //注销返回键
        document.addEventListener("backbutton", this.exitApp, false); //绑定退出事件
        //3秒后重新注册
        setTimeout(() => {
          document.removeEventListener("backbutton", this.exitApp, false); //绑定退出事件
          document.addEventListener("backbutton", this.eventBackButton, false); //返回键
        }, 3000);
      } else {
        this.$router.go(-1);
      }
    },
    exitApp() {
      // $vue.close();
      navigator.app.exitApp();
      // navigator.Backbutton.goHome(
      //   function() {
      //     console.log("go home success");
      //   },
      //   function() {
      //     console.log("go home fail");
      //   }
      // );
    },
    hotPush() {
      chcp.installUpdate(this.installationCallback);
      chcp.configure(
        {
          //"config-file": "http://qhsz.ecidi.com:8003/qhsz/chcp.json" // 热更新服务端
          // "config-file": "http://qhsz.simulate.com:8003/www/chcp.json"
           "config-file": "http://jgbim.qhfct.com:9000/qhszpm_hcp/chcp.json" //现场服务器热更新地址
        },
        this.configureCallback
      );
    },

    configureCallback(error) {
      if (error) {
        console.log("Error during the configuration process");
        console.log(error);
      } else {
        console.log("Plugin configured successfully");
        this.checkForUpdate();
      }
    },

    checkForUpdate() {
      chcp.fetchUpdate(this.fetchUpdateCallback);
    },

    fetchUpdateCallback(error, data) {
      let _this = this;
      if (error) {
        console.log("Failed to load the update with error code: " + error.code);
        console.log(error.description);
        if (
          error &&
          error.code == chcp.error.APPLICATION_BUILD_VERSION_TOO_LOW
        ) {
          this.$vux.confirm.show({
            // 组件除show外的属性
            title: "提示",
            content: "您的app版本过低，请升级",
            onCancel() {
              _this.exitApp();
            },
            onConfirm() {
              _this.userWentToStoreCallback();
            }
          });
        }
      }
      console.log(data);
    },

    installationCallback(error) {
      if (error) {
        console.log(
          "Failed to install the update with error code: " + error.code
        );
        console.log(error.description);
        this.onUpdated();
      } else {
        console.log("Update installed!");
        this.onUpdated();
      }
    },
    onUpdated() {
      navigator.splashscreen.hide();
    },
    userWentToStoreCallback() {
      cordova.InAppBrowser.open("https://xxxxxxxx/xxxxxxx", "_system", ""); //手机浏览器跳转地址
      //苹果商店轨道交通app https://itunes.apple.com/cn/app/id1459832528?mt=8
      this.exitApp();
    }
  },
  computed: {
    isLoading() {
      return this.$store.state.isLoading;
    },
    mainPop() {
      return this.$store.state.mainPop;
    },
    defaultPop() {
      return this.$store.state.defaultPop;
    },
    userId() {
      return this.$store.state.user.loginId;
    },
    roleIDs() {
      return this.$store.state.user.roleIDs;
    }
  },
  watch: {
    $route(to, from) {
      if (!from.name) {
        this.transitionName = "fade";
      } else if (to.name == "login") {
        this.transitionName = "slide-up";
      } else if (to.name == "noticeInfo") {
        this.transitionName = "fade";
      } else if (from.name == "login" || from.name == "noticeInfo") {
        this.transitionName = "slide-down";
      } else if (from.meta.index < to.meta.index) {
        this.transitionName = "slide-left-in";
      } else {
        this.transitionName = "slide-left-out";
      }
      if (from.meta.toast) {
        document.removeEventListener("backbutton", this.exitApp, false); //绑定退出事件
        document.addEventListener("backbutton", this.eventBackButton, false); //返回键
      }
    }
  }
};
</script>

<style lang="less">
@import "~vux/src/styles/reset.less";
</style>
